<?php

namespace app\admin\business;

use app\common\model\mysql\MallAdminUser as adminUserModel;

/**
 * 业务逻辑层 用于调用model层获取数据库数据进行组装处理以供控制器层使用
 */
class AdminUserService
{
	public $objAdminUser = null;
	public function __construct(){
		$this->objAdminUser = new adminUserModel();
	}

	// 登录相关的数据处理
	public function login($data){
		/*
		// 实例化用户model对象
		$objAdminUser = new adminUserModel();
		$adminUser = $objAdminUser->getAdminUserByUsername($data['username']);
		if(empty($adminUser) || $adminUser->status != config('status.mysql.normal')){
			//return show(config('status.error'),"不存在该用户");
			throw new \think\Exception("不存在该用户");
			
		}
		$adminUser = $adminUser->toArray();
		*/

		//通过用户名获取用户信息
		$adminUser = $this->getAdminUserByUsername($data['username']);
		if(empty($adminUser)){
			throw new \think\Exception("不存在该用户");
		}
		
		// 判断密码是否正确
		if($adminUser['password'] != md5($data['password'])){
			//return show(config('status.error'),"用户密码错误");
			throw new \think\Exception("用户密码错误");
		}

		$data = [
			'update_time' => time(),
			'last_login_time' => time(),
			'last_login_ip' => request()->ip(),
		];
		
		//更新用户登录信息
		$res = $this->objAdminUser->updateAdminUserByUserId($adminUser['id'],$data);
		if(empty($res)){
			//return show(config('status.error'),"更新失败");
			throw new \think\Exception("登录失败");
		}
		// 记录session
		session(config('admin.session_admin'),$adminUser);
		
		return true;
	}

	// 根据用户名获取登录用户相关信息数据
	public function getAdminUserByUsername($username){
		$adminUser = $this->objAdminUser->getAdminUserByUsername($username);
		if(empty($adminUser) || $adminUser->status != config('status.mysql.normal')){
			return [];
		}
		$adminUser = $adminUser->toArray();

		return $adminUser;
	}
}

